package io.shdxhl.simplerpc.code.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;

@Component(value = "simpleBeanFactory")
public class SimpleBeanFactory implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取匹配的bean
     * @param clazz
     * @return
     * @param <T>
     */
    public  static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 通过名称获取bean
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 获取所有的注释对象
     * @param annotation
     * @return
     */
    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotation) {
        return applicationContext.getBeansWithAnnotation(annotation);
    }

    /**
     * 注册新的bean
     * @param bean
     */
    public static void registerBean(Object bean) {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        //让bean完成spring初始化过程中所有增强器校验
        beanFactory.applyBeanPostProcessorsAfterInitialization(bean, bean.getClass().getName());
        beanFactory.registerSingleton(bean.getClass().getName(), bean);
    }
}
